/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package physical_spaces.business;

import Entity.ControlFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import physical_spaces.DAO.CreateControlFileDAO;

/**
 *
 * @author juan
 */
public class CreateControlFileBusiness {

    private String name;
    private String address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String createControlFile(List<ControlFile> controlFiles, Connection conn, String name, String address) {
        
        this.name = name;
        this.address = address;
        
        try {
            
            String sql;
            
            CreateControlFileDAO controlFileDAO = new CreateControlFileDAO();
            sql = "ALTER SYSTEM SET CONTROL_FILES = ";
            
            for(ControlFile file : controlFiles)
                sql = sql + "'" + file.getName() + "',";
            
            sql = sql +  "'" + address + name + ".CTL' scope=spfile";
            System.out.println(sql);
            
            controlFileDAO.CreateControlFile(sql, conn);
            controlFileDAO.stopDatabase();
            copyControlFile();
            
            return "logout";

        } catch (SQLException ex) {
            Logger.getLogger(CreateControlFileBusiness.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;

    }

    public void copyControlFile() {
        
        File origen = new File(address + "CONTROL01.CTL");
        File destino = new File(address + name + ".CTL");

        try {
            InputStream in = new FileInputStream(origen);
            OutputStream out = new FileOutputStream(destino);

            byte[] buf = new byte[1024];
            int len;

            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

            in.close();
            out.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

}